<?php


namespace App\service;

use App\Http\Controllers\OrderGoods;
use App\Models\GrGood;
use App\Models\OrderGood;
use App\Models\Orders;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Yansongda\Pay\Pay;

class AlipayController
{
    protected $config = [
        'alipay' => [
            'default' => [
                // 必填-支付宝分配的 app_id
                'app_id' => '2021000119690344',
                // 必填-应用私钥 字符串或路径
                'app_secret_cert' => 'MIIEpAIBAAKCAQEAkFm2frsw+p88/d+cbFcECa+FEpKm9R8X2XRwjM+BjqhNvdKqYVdVtwu8X2jyYUEdl3zWegpqrkEqKBnkb7Y6/up7+ZJQb/cnLHpz+wmFvyQ7F8mNNiR5T8FF8GsnkH2S1egTEXYo1Kq5h+lOzg44rdOvWzaL7V2Cl5x3XDpRkgGSVBv4XyOQAHrQnl6kFVRCT3HBgy8JHeIDtIdDkwi5bm905L2P1yPIPLGw4qpnMzcvLd28xcul3ZruMo8VXmGQn9iUd3hsz2p9BsoU0Fwwyj/LLu4wb06elpfqAXs8wF5NT18jwhqT1Sxoowl2SWaQI7NSaS7Y99XP6+UrwRt9LQIDAQABAoIBAC/80xGAc4DtzR3s55iQuPPrWMba4AwfIROWhRAar8xYITgYv7GKkiE/Eol5XxJ7zjWdN8PskJiLa1NXgDyvDR/PnhVS0dDXDjvYHZR4DvGDPu3igEJej8G20+RgCxAa3uSjuSsV5+8DLpiDNEKGMct/0wz0rkHj01VJm9iaPqHVyhnwFlYoLwZKuHBBdJ5IVDSqRBaOx9V925fKH4hp9I7Pr5foMrw6nVDvbZXCwqLqVdYu505+zPBZ9I/ki19b5ZARIZSveeoPa0BB/YRGfo4unG0jaH2GEfv4QFr9hUHCxYK7Vqj4h5+88+oysKsv6lM4hWKSkomIT9KGzWAJZOECgYEAwSzs2OXHbGupyN3BAEnCXsB/xhMv2vbPjLp5s0ttMbZIQWvsPpe80FA0UL6N5D8+A1H64w5CDtbECNZiRUXDRSXvvIvvM/eCY0nqflwVhNwUUdYAxSBJH4CDfcxYAw78FVV3vJ66HMv5smuuvXoqAEOBIllw2wP54ldx/Z7iNOkCgYEAv0vLlZth1e5O+KddsnZh0DrAAwS1O21Uas7K17PSChD1LQ+oDh06ju4ROKWL9PHe0ZafSA7E5kSNZmDTrF17j/fW2KyaB4iW4UhAJCJUnvlIkmnQdaBHXJZgay62NGzwWFGAvMf+bTuxf+3KnrPCBpLt1IPhgudt4ko3j6xia6UCgYBEPsvaAKuIeSy9YuJZaLV7ZgR+BK9GayV98S8nkYEdK+mw+yC2KEMzUPJ6iCd2uIT/BUpeRt49gdA10w9aq7/FwRZGBSXXtRxiWW23gG61xk6DbthMzBApSeyqV7PMONID83LetzDHFaS8TOCp3evStgZ8DR8asPfp57zEvgnqaQKBgQCUkbZczB/w+bOFtN61YvHWujo0Xeyvadr9VPv/CN6hCMiSJa28wIChT046s3/+TfdiyduNKENOH4G+OIdNQBFeH/tRrsO2BCRCdU2zgqI8EZmGdP38zO1/gB8EP3QtRUppHWuhsqXsikbx92m9Vhjj6CskOQTlGP6jmEaMpDKQLQKBgQCLZunvUbQ8mXv/ES/VC0svOGeT71WYpj/+6J2x86ovp1IW+/qvwTkXxGVAPK9CuvBMKs0UE71tMeh47DptVQT8sq5wlDHe90jvC20fTdq3J6ru6AD0w/ApRcriTp5i129ifs6TzxcEuAmzQrzqsplgE7XhMPR4qhwmJsU/tzEYlw==',
                // 必填-应用公钥证书 路径
                'app_public_cert_path' => 'pay/appCertPublicKey_2021000119690344.crt',
                // 必填-支付宝公钥证书 路径
                'alipay_public_cert_path' => 'pay/alipayCertPublicKey_RSA2.crt',
                // 必填-支付宝根证书 路径
                'alipay_root_cert_path' => 'pay/alipayRootCert.crt',
                'return_url' => 'http://www.day15.com/returnCallback',
                'notify_url' => 'http://www.day15.com/notifyCallback',
                // 选填-服务商模式下的服务商 id，当 mode 为 Pay::MODE_SERVICE 时使用该参数
                'service_provider_id' => '',
                // 选填-默认为正常模式。可选为： MODE_NORMAL, MODE_SANDBOX, MODE_SERVICE
                'mode' => Pay::MODE_SANDBOX,
            ],
        ],
        'logger' => [ // optional
            'enable' => false,
            'file' => './logs/alipay.log',
            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
    ];

    //支付

    public function web($total_money, $order_sn)
    {
        $result = Pay::alipay($this->config)->web([
            'out_trade_no' => $order_sn,
            'total_amount' => $total_money,
            'subject' => '像李乐家付款',
        ]);
        return $result;
    }

    //验证
    public function returnCallback()
    {
        $data = Pay::alipay($this->config)->callback(); // 是的，验签就这么简单！
        //开启事物
        DB::beginTransaction();
        try {
            $res = Orders::where('order_sn', $data->out_trade_no)
                ->update(['order_status' => 1, 'is_pay' => 1, 'created_at' => date('Y-m-d H:i:s'), 'pay_type' => 0]);
            if ($res) {
                $orderData = Orders::where('order_sn', $data->out_trade_no)->first();
                $data = \App\Models\OrderGoods::join('gr_goods', 'gr_order_goods.goods_id', '=', 'gr_goods.goods_id')
                    ->where('gr_order_goods.order_id', $orderData->id)->get()->toArray();
                foreach ($data as $k => $v) {
                    $res = GrGood::where('goods_id', $v['goods_id'])->update(['stock_total' => $v['stock_total'] - $v['goods_number']]);
                }
            }
            //提交
            DB::commit();
            if ($res) {
                echo "支付成功";
            } else {
                echo "支付失败";
            }
        } catch (\Exception $e) {
            //回滚事务
            Db::rollback();
        }
        // dd($data->trade_no);
        // 订单号：$data->out_trade_no
        // 支付宝交易号：
        // 订单总金额：$data->total_amount
    }

    //异步
    public function notifyCallback()
    {
        $alipay = Pay::alipay($this->config);

        try {
            $data = $alipay->callback(); // 是的，验签就这么简单！
            dd($data);
            // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
            // 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额）；
            // 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）；
            // 4、验证app_id是否为该商户本身。
            // 5、其它业务逻辑情况
        } catch (\Exception $e) {
            // $e->getMessage();
        }

        return $alipay->success();
    }

    //退款
    public function refund($order_sn, $money)
    {

        $result = Pay::alipay($this->config)->refund([
            'out_trade_no' => $order_sn,
            'refund_amount' => $money,
        ]);
        return $result;

    }
}
